<template>
  <div class="tinymce-class">
    <editor :id="id" v-model="myValue" :init="init" :disabled="disabled" @onClick="onClick" class="tinymce-editor">
    </editor>
    <div v-show="isMenuVisible" class="menu" :style="menuStyle">
      <!-- 菜单内容 -->
      <span @click="doAction">自定义选中</span>
    </div>
  </div>
</template>

<script>
// 引入组件
import tinymce from 'tinymce'
import editor from '@tinymce/tinymce-vue'

// 引入富文本编辑器主题的js和css
// import 'tinymce/skins/content/default/content.css'
import 'tinymce/themes/silver'
// import 'tinymce/icons/default/icons' // 解决了icons.js 报错问题，不用定制icon可以忽略

// 编辑器扩展插件plugins
import 'tinymce/plugins/paste' // 粘贴插件
import 'tinymce/plugins/image' // 上传图片插件
import 'tinymce/plugins/media'// 插入视频插件
import 'tinymce/plugins/link' // 超链接
import 'tinymce/plugins/code' // 源码
import 'tinymce/plugins/table' // 插入表格插件
import 'tinymce/plugins/lists' // 列表插件
import 'tinymce/plugins/wordcount' // 字数统计插件
import 'tinymce/plugins/preview' // 预览

// import 'tinymce/plugins/table'
import 'tinymce/plugins/lists'
import 'tinymce/plugins/colorpicker'
import 'tinymce/plugins/textcolor'
import "tinymce/plugins/code";
import "tinymce/plugins/link";
import "tinymce/plugins/advlist";
import "tinymce/plugins/anchor";
import "tinymce/plugins/codesample";
import "tinymce/plugins/hr";
import "tinymce/plugins/fullscreen";
import "tinymce/plugins/textpattern";
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/autolink";
import "tinymce/plugins/directionality";
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/template";
import "tinymce/plugins/charmap";
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/insertdatetime";
import "tinymce/plugins/autoresize";
import "tinymce/plugins/pagebreak";
import "tinymce/plugins/print";
import "tinymce/plugins/save";
import "tinymce/plugins/tabfocus";
import "tinymce/plugins/bbcode";

// import 'tinymce/plugins/contextmenu'
// import "tinymce/plugins/imagetools";
// import "tinymce/plugins/autosave";
// import "tinymce/plugins/emoticons";
// import "tinymce/plugins/spellchecker";


import plugins from './plugins'
import toolbar from './toolbar'
import htmlDocx from 'html-docx-js/dist/html-docx';

export default {
  name: 'tinymce',
  components: { editor },
  props: {
    value: {
      // 默认的富文本内容
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    disabled: {
      // 禁用
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      init: {
        language_url: '/tinymce/langs/zh_CN.js', // 语言包路径
        language: 'zh_CN', // 语言
        skin_url: '/tinymce/skins/ui/oxide', // 主题路径
        content_css: '/tinymce/skins/ui/oxide/content.css', // 为编辑区指定css文件,该参数的值是你的css文件路径，可使用绝对路径或相对路径。
        plugins: plugins, // 指定需加载的插件
        toolbar: toolbar, // 自定义工具栏
        toolbar_mode: 'sliding', // 工具栏模式
        paste_data_images: true, // 允许粘贴图片
        branding: false, // 不显示富文本支持方
        statusbar: false, // 隐藏状态栏
        menubar: false, // 禁用菜单栏
        theme: 'silver', // 默认主题
        placeholder: '请输入',
        contextmenu: false, // 禁用右键菜单
        fontsize_formats: "12px 14px 16px 18px 20px 22px 24px 36px 48px 56px 72px",
        font_formats: "宋体='宋体';仿宋='仿宋';微软雅黑='微软雅黑';楷体='楷体';隶书='隶书';幼圆='幼圆';Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Helvetica=helvetica;",
        zIndex: 1101,
        icons_url: '/tinymce/js/customIcons.js',  // 指向你的自定义图标JS文件
        icons: 'customIcons',  // 使用自定义图标集
        init_instance_callback: (editor) => {
          this.editor = editor;
        },
        setup: (editor) => {
          editor.on('mouseup', (e) => {
            this.tinymceMouseup(e);
          });
          editor.on('selectionchange', () => {
            const text = editor.selection.getContent({ format: 'text' });
            this.updateMenuVisibilityAndPosition(editor, text);
          });
          // 自定义菜单 下载
          editor.ui.registry.addButton('exportAItext', {
            icon: 'export',
            tooltip: '下载',
            onAction: () => {
              this.exportToWord();
            }
          });
        }
      },
      myValue: this.value,
      decoder: new TextDecoder('utf-8'),
      editor: null,
      menuStyle: {
        position: 'absolute',
        top: '0px', // 初始位置，稍后在方法中更新  
        left: '0px' // 初始位置，稍后在方法中更新  
      },
      isMenuVisible: false,
      checkContent: '',
    }
  },
  beforeDestroy() {
    tinymce.remove()
  },
  created() { },
  mounted() {
    tinymce.init({})
  },
  computed: {},
  watch: {
    value(newValue) {
      this.myValue = newValue
    },
    myValue(newValue) {
      this.$emit('input', newValue)
    },

  },
  methods: {
    onClick(e) {
      this.$emit('onClick', e, tinymce)
    },
    async fuzhi() {
      let data = {
        content: ""
      };
      const response = await fetch('你的接口', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
      });
      const reader = response.body.getReader();
      while (true) {
        const { done, value } = await reader.read();
        if (done) {
          break;
        }
        const chunk = this.decoder.decode(value, { stream: true });
        this.updateEditorContent(chunk)
      }
    },
    // 流式传输赋值
    updateEditorContent(text) {
      this.editor.execCommand('mceInsertContent', false, text);
    },
    updateMenuVisibilityAndPosition(editor, selectedText) {
      this.checkContent = selectedText;
    },
    // 自定义按钮 下载
    exportToWord() {
      // 从 TinyMCE 获取 HTML 内容
      const htmlContent = this.editor.getContent({ format: 'raw' });
      // 使用 html-docx-js 将 HTML 转换为 Word 文档
      const docx = htmlDocx.asBlob(htmlContent, { filename: 'document.docx' });
      // 创建一个链接元素用于下载
      const url = URL.createObjectURL(docx);
      const a = document.createElement('a');
      a.href = url;
      a.download = 'download.docx'; // 设置下载的文件名
      a.click(); // 触发点击事件开始下载
      URL.revokeObjectURL(url); // 清理对象URL
    },
    tinymceMouseup(e) {
      this.menuStyle.top = `${e.y + 110}px`
      if (this.editingAreaWidth == '62.5%') {
        this.menuStyle.left = `230px`
      } else {
        this.menuStyle.left = `615px`
      }

      if (this.checkContent.length > 0) {
        this.isMenuVisible = true;
      } else {
        this.isMenuVisible = false;
      }
    },
    doAction() {
      // 执行你想要的动作  

    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .tox .tox-tbtn--select {
  width: 100px;
}

::v-deep .tox .tox-sidebar-wrap {
  width: 100%;
  padding: 50px;
  display: flex;
  justify-content: center;
}

::v-deep .tox-edit-area {
  // min-height: 900px;
  width: 800px;
  // margin-top: 20px;
  overflow: auto !important;
  flex: none !important;
  background-color: #fff !important;
  border: 1px solid #e8e8e8;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.12);
  scroll-behavior: smooth;
}

::v-deep .tox-tinymce {
  border: none;
  overflow: auto;
}

::v-deep .tox-toolbar {
  border: 0.5px solid #ccc;
  background: none;
  border-bottom: none;
  justify-content: center;
}

::v-deep .tox-editor-container {
  // align-items: center;
  // height: calc(100% - 40px);
  background-color: rgb(245, 245, 245);
  overflow-y: auto;
  position: relative;
}

::v-deep .tox-editor-header {
  width: 100%;
}

.tinymce-class {
  margin: 0px;
  padding: 0px;
  width: calc(100% - 0px);
  height: 100%;
  left: 0px;
  top: 56px;
  bottom: 0px;
}

.tinymce-class :global(.tox-tinymce) {
  height: 100% !important;
}

.tinymce-class :global(hr) {
  border-color: red !important;
  border-style: solid;
  border-width: 6px 0 0 0 !important;
}

.menu {
  background-color: white;
  border: 1px solid #ccc;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  padding: 5px;
  /* 其他样式 */
  font-size: 16px;

  span {
    cursor: pointer;
    padding: 0 12px;
  }
}
</style>


<style lang="scss">
// tinymce弹框遮罩层 
div.mce-reset.mce-fade.mce-in {
  z-index: 3999 !important;
}

// tinymce弹框 
div.mce-container.mce-panel.mce-floatpanel.mce-window.mce-in {
  z-index: 4000 !important;
}

.tox-tinymce-aux {
  z-index: 99999 !important;
}
</style>